<template>
  <div class="user-modal">
    <el-form ref="formRef" :model="formData" :rules="rules" label-width="90px" style="padding: 12px 20px;">
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="formData.email" placeholder="请输入邮箱" />
      </el-form-item>
      <el-form-item label="用户名" prop="username">
        <el-input v-model="formData.username" placeholder="请输入用户名" />
      </el-form-item>
      <el-form-item v-if="!isEdit" label="密码" prop="password">
        <el-input v-model="formData.password" type="password" placeholder="设置初始密码" />
      </el-form-item>
      <el-form-item label="角色" prop="role">
        <el-select v-model="formData.role" placeholder="请选择角色" style="width: 100%">
          <el-option v-for="opt in ROLE_OPTIONS" :key="opt.value" :label="opt.label" :value="opt.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="isActive">
        <el-switch v-model="formData.isActive" />
      </el-form-item>
    </el-form>
    <div class="modal-footer">
      <el-button @click="handleCancel">取消</el-button>
      <el-button type="primary" @click="handleConfirm" :loading="loading">{{ isEdit ? '保存' : '创建' }}</el-button>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { ROLE_OPTIONS } from '@/utils/roles'

const props = defineProps({
  isEdit: { type: Boolean, default: false },
  editData: { type: Object, default: () => ({}) }
})
const emit = defineEmits(['close'])

const formRef = ref(null)
const loading = ref(false)

const formData = ref({
  email: props.editData?.email || '',
  username: props.editData?.username || '',
  password: '',
  role: props.editData?.role || 'project_user',
  isActive: props.editData?.isActive !== undefined ? props.editData.isActive : true
})

const rules = {
  email: [ { required: true, message: '请输入邮箱', trigger: 'blur' }, { type: 'email', message: '邮箱格式不正确', trigger: ['blur','change'] } ],
  username: [ { required: true, message: '请输入用户名', trigger: 'blur' } ],
  password: props.isEdit ? [] : [ { required: true, message: '请输入密码', trigger: 'blur' }, { min: 6, message: '不少于6位', trigger: 'blur' } ],
  role: [ { required: true, message: '请选择角色', trigger: 'change' } ]
}

const handleConfirm = async () => {
  if (!formRef.value) return
  loading.value = true
  try {
    await formRef.value.validate((valid) => {
      if (valid) {
        const payload = { email: formData.value.email, username: formData.value.username, role: formData.value.role, isActive: formData.value.isActive }
        if (!props.isEdit) payload.password = formData.value.password
        emit('close', payload)
      }
    })
  } finally {
    loading.value = false
  }
}

const handleCancel = () => emit('close')
</script>

<style scoped>
.modal-footer { display:flex; justify-content:flex-end; gap:12px; padding: 8px 16px; border-top:1px solid #e4e7ed; }
</style>


